import Scrollbar from '@renderer/components/Scrollbar'
//import { useEyedropperService } from '@renderer/services/eyedropper'
import { Tooltip } from 'antd'
import {
  Camera,
  ClipboardList,
  Cpu,
  FileText,
  FolderOpen,
  Languages,
  Lightbulb,
  MessageSquare,
  Pen,
  Settings
} from 'lucide-react'
import { Dispatch, SetStateAction, useImperativeHandle, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import styled from 'styled-components'

// Extend the Window interface to include showToast
declare global {
  interface Window {
    showToast?: (msg: string) => void
  }
}

// 功能菜单组件的Props类型定义
// 移除 FileSearchDialog 的导入
// import FileSearchDialog from '@renderer/components/FileSearchDialog'

// 修改 Props 类型
interface FeatureMenusProps {
  text: string
  setRoute: Dispatch<SetStateAction<'translate' | 'summary' | 'chat' | 'explanation' | 'home' | 'file-search'>>
  onSendMessage: (prompt?: string) => void
}

const FeatureMenus = ({
  ref,
  text,
  setRoute,
  onSendMessage
}: FeatureMenusProps & { ref?: React.RefObject<FeatureMenusProps | null> }) => {
  const { t } = useTranslation()
  const [selectedIndex, setSelectedIndex] = useState(-1)
  // 移除 fileSearchVisible 状态

  // 定义围绕大语言模型的功能菜单项
  const aiFeatures = useMemo(
    () => [
      {
        // 图标大小调整为20px
        icon: <MessageSquare size={20} color="var(--color-text)" />,
        title: t('miniwindow.feature.chat'),
        active: true,
        onClick: () => {
          if (text) {
            setRoute('chat') // 切换到 chat 路由（页面/模式）
            onSendMessage() // 调用父组件传入的 onSendMessage 方法
          }
        }
      },
      {
        icon: <Languages size={20} color="var(--color-text)" />,
        title: t('miniwindow.feature.translate'),
        onClick: () => text && setRoute('translate')
      },
      {
        icon: <FileText size={20} color="var(--color-text)" />,
        title: t('miniwindow.feature.summary'),
        onClick: () => {
          if (text) {
            setRoute('summary')
            onSendMessage(t('prompts.summarize'))
          }
        }
      },
      {
        icon: <Lightbulb size={20} color="var(--color-text)" />,
        title: t('miniwindow.feature.explanation'),
        onClick: () => {
          if (text) {
            setRoute('explanation')
            onSendMessage(t('prompts.explanation'))
          }
        }
      }
      // {
      //   icon: <Camera size={16} color="var(--color-text)" />,
      //   title: '截图悬浮',
      //   onClick: async () => {
      //     if (window.api?.screenshotFloat) {
      //       await window.api.screenshotFloat()
      //     } else {
      //       alert('window.api.screenshotFloat 未定义')
      //     }
      //   }
      // }
    ],
    [onSendMessage, setRoute, t, text]
  )

  // 定义围绕本地插件的功能菜单项
  // 定义围绕本地插件的功能菜单项
  const localPluginFeatures = useMemo(
    () => [
      {
        icon: <FolderOpen size={20} color="var(--color-text)" />,
        title: t('本地检索') || '文件',
        onClick: () => {
          // 使用路由切换
          setRoute('file-search')
        }
      },
      {
        icon: <Camera size={16} color="var(--color-text)" />,
        title: '截图悬浮',
        onClick: async () => {
          if (window.api?.screenshotFloat) {
            await window.api.screenshotFloat()
          } else {
            alert('window.api.screenshotFloat 未定义')
          }
          console.log('截图悬浮功能点击')
        }
      },
      {
        key: 'eyedropper',
        icon: <Pen size={22} />, // lucide-react 取色器图标
        title: '取色器',
        onClick: async () => {
          // 1. 用户手动截图（区域截图/全屏截图）
          let base64 = null
          try {
            base64 = await window.api.eyedropper.regionScreenshot()
          } catch (e) {
            window.showToast?.('截图失败')
            return
          }
          if (!base64) {
            window.showToast?.('截图失败')
            return
          }
          // 2. 弹窗显示截图图片，用户点击像素点自动复制
          await window.api.eyedropper.openWindow(base64)
          // 取色和复制逻辑在 eyedropper.html 内部已实现
          window.showToast?.('请在弹窗中点击像素点进行取色')
        }
      },
      {
        key: 'ocr',
        icon: <FileText size={22} color="var(--color-text)" />, // lucide-react 文字识别图标
        title: 'OCR文字识别',
        onClick: async () => {
          window.showToast?.('开始截图...')
          let base64 = null
          try {
            base64 = await window.api.eyedropper.regionScreenshot()
          } catch (e) {
            window.showToast?.('截图失败: ' + ((e as Error)?.message || e))
            return
          }
          if (!base64) {
            window.showToast?.('截图失败')
            return
          }
          window.showToast?.('正在识别文字...')
          try {
            const result = await window.api.ocr.recognize(base64)
            if (typeof result === 'string') {
              window.showToast?.('识别结果已复制')
              navigator.clipboard.writeText(result)
              // 可扩展弹窗展示 result
            } else if (result?.error) {
              window.showToast?.('识别失败: ' + result.error)
            } else {
              window.showToast?.('识别失败')
            }
          } catch (err) {
            window.showToast?.('识别异常: ' + ((err as any)?.message || err))
          }
        }
      },
      {
        icon: <ClipboardList size={20} color="var(--color-text)" />,
        title: t('剪贴板历史') || '剪贴板历史',
        onClick: () => {
          window.api?.clipboardHistory?.openWindow()
        }
      },
      {
        icon: <Cpu size={20} color="var(--color-text)" />,
        title: t('待扩展') || '插件',
        onClick: () => {
          // 插件功能的点击处理逻辑
          console.log('插件功能点击')
        }
      },
      {
        icon: <Settings size={20} color="var(--color-text)" />,
        title: t('待扩展') || '设置',
        onClick: () => {
          // 设置功能的点击处理逻辑
          console.log('设置功能点击')
        }
      }
    ],
    [t, setRoute]
  )

  // 合并所有功能菜单项
  const features = useMemo(() => [...aiFeatures, ...localPluginFeatures], [aiFeatures, localPluginFeatures])

  useImperativeHandle(ref, () => ({
    text,
    setRoute,
    onSendMessage,
    nextFeature() {
      setSelectedIndex((prev) => (prev < features.length - 1 ? prev + 1 : 0))
    },
    prevFeature() {
      setSelectedIndex((prev) => (prev > 0 ? prev - 1 : features.length - 1))
    },
    useFeature() {
      features[selectedIndex].onClick?.()
    },
    resetSelectedIndex() {
      setSelectedIndex(0)
    }
  }))

  // 渲染功能菜单列表
  return (
    <>
      <FeatureList>
        <Scrollbar>
          <FeatureListWrapper>
            {/* AI 功能区块标题 */}
            <SectionTitle>AI 功能</SectionTitle>
            <IconButtonRow>
              {aiFeatures.map((feature, index) => (
                <Tooltip title={feature.title} placement="bottom" key={`ai-${index}`}>
                  <FeatureIconButton
                    onClick={() => {
                      setSelectedIndex(index) // 点击时才高亮
                      feature.onClick()
                    }}
                    className={selectedIndex === index ? 'active' : ''}
                    tabIndex={0}
                    aria-label={feature.title}>
                    {feature.icon}
                  </FeatureIconButton>
                </Tooltip>
              ))}
            </IconButtonRow>
            <SectionTitle>本地插件</SectionTitle>
            <IconButtonRow>
              {localPluginFeatures.map((feature, index) => (
                <Tooltip title={feature.title} placement="bottom" key={`plugin-${index}`}>
                  <FeatureIconButton
                    onClick={() => {
                      setSelectedIndex(aiFeatures.length + index) // 点击时才高亮
                      feature.onClick()
                    }}
                    className={selectedIndex === aiFeatures.length + index ? 'active' : ''}
                    tabIndex={0}
                    aria-label={feature.title}>
                    {feature.icon}
                  </FeatureIconButton>
                </Tooltip>
              ))}
            </IconButtonRow>
          </FeatureListWrapper>
        </Scrollbar>
      </FeatureList>
    </>
  )
}
FeatureMenus.displayName = 'FeatureMenus'

// 区块标题样式
const SectionTitle = styled.h4`
  margin: 4px 0;
  font-size: 14px; /* 标题字体更大 */
  color: var(--color-text-secondary);
  font-weight: bold;
`

// 图标按钮样式
const FeatureIconButton = styled.div`
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: all 0.2s;
  background: var(--color-background-opacity);
  border: none;
  padding: 4px; /* 内边距适中 */
  border-radius: 5px;
  position: relative;
  -webkit-app-region: none;
  user-select: none;
  width: 44px; /* 按钮宽度适中 */
  height: 44px; /* 按钮高度适中 */
  margin: 0px;

  &:hover {
    background: var(--color-primary-opacity);
    transform: translateY(-1px);
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

    svg {
      color: var(--color-primary) !important;
    }
  }

  &.active {
    background: var(--color-primary-opacity);
    transform: translateY(-1px);
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  }
`

// 横向按钮排列容器
const IconButtonRow = styled.div`
  display: flex;
  flex-direction: row;
  gap: 12px; /* 按钮间距适中 */
  margin-bottom: 8px;
`

// 菜单列表容器样式
const FeatureListWrapper = styled.div`
  display: flex;
  flex-direction: column;
  padding: 4px 4px 0px 4px; /* 内边距更大 */
  cursor: pointer;
`

// FeatureList 只做外层容器，不再继承 Scrollbar
const FeatureList = styled.div`
  flex-shrink: 0;
  height: auto;
  -webkit-app-region: none;
`

export default FeatureMenus

// FeatureMenus 的父组件是 HomeWindow.tsx
// 路径为：f:\AI\cherry-studio-main\src\renderer\src\windows\mini\home\HomeWindow.tsx
// 在 HomeWindow 组件中通过如下方式引用和使用：
// <FeatureMenus setRoute={setRoute} onSendMessage={onSendMessage} text={content} ref={featureMenusRef} />
